<?php
require_once '../includes/functions.php';
check_login();

header('Content-Type: application/json');

// 获取POST数据
$data = json_decode(file_get_contents('php://input'), true);

if (!isset($data['username']) || !isset($data['currentPassword'])) {
    http_response_code(400);
    echo json_encode(['error' => '参数错误']);
    exit;
}

$username = trim($data['username']);
$current_password = $data['currentPassword'];
$new_password = isset($data['newPassword']) ? trim($data['newPassword']) : '';

// 验证用户名长度
if (strlen($username) < 3) {
    http_response_code(400);
    echo json_encode(['error' => '用户名长度不能小于3个字符']);
    exit;
}

// 验证新密码长度（如果提供了新密码）
if ($new_password && strlen($new_password) < 6) {
    http_response_code(400);
    echo json_encode(['error' => '新密码长度不能小于6个字符']);
    exit;
}

// 获取当前凭据
$credentials = get_admin_credentials();

// 验证当前密码
if (!password_verify($current_password, $credentials['password']) && 
    !($current_password === 'admin' && $credentials['password'] === 'admin')) {
    http_response_code(400);
    echo json_encode(['error' => '当前密码错误']);
    exit;
}

// 保存新的凭据
$save_result = save_admin_credentials(
    $username,
    $new_password ? $new_password : ($credentials['password'] === 'admin' ? 'admin' : $current_password)
);

if ($save_result) {
    // 更新会话中的用户名
    $_SESSION['username'] = $username;
    echo json_encode(['success' => true]);
} else {
    http_response_code(500);
    echo json_encode(['error' => '保存失败']);
}
